/*
* @(#)ListUserRecordAction.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
*/

package com.dcivision.workflow.web;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.workflow.bean.MtmWorkflowStepWorkflowStep;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.bean.WorkflowStepFormEquat;
import com.dcivision.workflow.bean.WorkflowStepRoute;
import com.dcivision.workflow.core.WorkflowOperationManager;
import com.dcivision.workflow.dao.MtmWorkflowStepUserActorDAObject;
import com.dcivision.workflow.dao.MtmWorkflowStepWorkflowStepDAObject;
import com.dcivision.workflow.dao.WorkflowStepDAObject;
import com.dcivision.workflow.dao.WorkflowStepFormEquatDAObject;
import com.dcivision.workflow.dao.WorkflowStepRouteDAObject;

/**
 * <p>Class Name:       MaintWorkflowConnectionAction    </p>
 * <p>Description:      save the connections</p>
 *
 * @author           Zealot Shi
 * @company          DCIVision Limited
 * @creation date    02/11/2004
 * @version          $Revision: 1.9.26.1 $
 */
public class MaintWorkflowConnectionAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.9.26.1 $";


  /** Creates a new instance of ListWorkflowGroupAction */
  public MaintWorkflowConnectionAction() {
    super();
    //this.setListName("workflowGroupList");
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.workflow.dao.WorkflowGroupDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.WORKFLOW_RECORD);
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try{
      Map mapDS = mapping.getModuleConfig().findDataSourceConfig("org.apache.struts.action.DATA_SOURCE").getProperties();
      
      MaintWorkflowConnectionForm maintWorkflowConnectionForm = (MaintWorkflowConnectionForm)form;
      String chartXml = maintWorkflowConnectionForm.getWorkflowChart();     
      String url = SystemParameterFactory.getSystemParameter(SystemParameterConstant.APPLICATION_BASE_URL);
      String[] urlMessage = url.split("/");
      String projectName = urlMessage[urlMessage.length-1];
      String filePath = SystemParameterFactory.getSystemParameter(SystemParameterConstant.WORKFLOW_ATTACHMENT_PHYSICAL_PATH)+"/"+projectName;
      File pathFile = new File(filePath);
      
      if(!pathFile.exists()){
        pathFile.mkdir(); 
      }
      PrintWriter out
           = new PrintWriter(new BufferedWriter(new FileWriter(filePath+"/"+maintWorkflowConnectionForm.getWorkflowRecordID()+".xml")));
      out.write(chartXml);
      out.close();
      super.execute(mapping, form, request, response);
    }catch(Exception e){
      log.error(e, e);   
    }
    return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
  }
  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    try{
      WorkflowOperationManager operationManager = new WorkflowOperationManager(this.getSessionContainer(request), this.getConnection(request));
    
    MtmWorkflowStepWorkflowStepDAObject stepStepDAO =  (MtmWorkflowStepWorkflowStepDAObject) this.getDAObjectByClassName(request, "com.dcivision.workflow.dao.MtmWorkflowStepWorkflowStepDAObject");
    MtmWorkflowStepUserActorDAObject stepActorDAO = (MtmWorkflowStepUserActorDAObject) this.getDAObjectByClassName(request, "com.dcivision.workflow.dao.MtmWorkflowStepUserActorDAObject");
    WorkflowStepDAObject stepDAO = new WorkflowStepDAObject(this.getSessionContainer(request), this.getConnection(request));
    WorkflowStepRouteDAObject wfStepRouteDAO = (WorkflowStepRouteDAObject) this.getDAObjectByClassName(request, "com.dcivision.workflow.dao.WorkflowStepRouteDAObject");
    WorkflowStepFormEquatDAObject formEquatDAO = (WorkflowStepFormEquatDAObject) this.getDAObjectByClassName(request, "com.dcivision.workflow.dao.WorkflowStepFormEquatDAObject");
    MaintWorkflowConnectionForm maintForm = (MaintWorkflowConnectionForm)form;
    String[] parentStepSeq = maintForm.getParentStepSeq();
    String[] childStepSeq = maintForm.getChildStepSeq();
    String[] parentStepType = maintForm.getParentStepType();
    String[] stepSeq = maintForm.getStepSeq();
    String[] parentStepActionType = maintForm.getParentStepActionType();
    String[] loopBack = maintForm.getLoopBack();
    String workflowRecordID = maintForm.getWorkflowRecordID();
    stepStepDAO.deleteListByWorkflowRecordID(new Integer(workflowRecordID));
    stepStepDAO.deleteUnusedStepsByWorkflowRecordID(new Integer(workflowRecordID), stepSeq);
    //delete the old routes
    for(int i=0;i<parentStepSeq.length;i++)
    {
      MtmWorkflowStepWorkflowStep  mtmWorkflowStepWorkflowStep = new MtmWorkflowStepWorkflowStep();
      Integer parentStepID = stepDAO.getStepIDByWorkflowIDAndStepSeq(new Integer(workflowRecordID), new Integer(parentStepSeq[i]));
      wfStepRouteDAO.deleteByWorkflowStepID(parentStepID);
      formEquatDAO.deleteByWorkflowStepID(parentStepID);
    }    
    for(int i=0;i<parentStepSeq.length;i++)
    {
      MtmWorkflowStepWorkflowStep  mtmWorkflowStepWorkflowStep = new MtmWorkflowStepWorkflowStep();
      Integer parentStepID = stepDAO.getStepIDByWorkflowIDAndStepSeq(new Integer(workflowRecordID), new Integer(parentStepSeq[i]));
        
        if("U".equals(parentStepType[i].substring(0,1))){
          String routeName = parentStepType[i].substring(2);
          
          Integer nextRouteSeq = wfStepRouteDAO.getNextSeqNumber(parentStepID);
          if(nextRouteSeq==null){
            nextRouteSeq = new Integer(0);
          }
          WorkflowStepRoute tmpRoutine = new WorkflowStepRoute();
          tmpRoutine.setWorkflowStepID(parentStepID);
          tmpRoutine.setRouteSeq(nextRouteSeq);
          tmpRoutine.setRouteName(routeName);
          wfStepRouteDAO.insertObject(tmpRoutine);
          mtmWorkflowStepWorkflowStep.setParentType(WorkflowStep.PARENT_TYPE_SINGLE + nextRouteSeq.toString());
        } else if(WorkflowStep.PARENT_TYPE_FROM_VALUE_DRIVEN.equals(parentStepType[i].substring(0,1))){
          String routeName = TextUtility.splitString(parentStepType[i].substring(2),"#")[0];
          String equation = TextUtility.splitString(parentStepType[i].substring(2),"#")[1];                    

          //Insert the form equation into Workflow_Step_Form_Equation Table
          //String formEquationListValue = request.getParameter("formEquationListValue");

          //String[] formEquationArr = TextUtility.splitString(formEquationListValue, "$$");
          String[] elementArr = TextUtility.splitString(equation,";");
          Integer nextRouteSeq = formEquatDAO.getNextSeqNumber(parentStepID);
          //if(!Utility.isEmpty(compare)){
          WorkflowStepFormEquat formEquat = new WorkflowStepFormEquat();
          formEquat.setWorkflowStepID(parentStepID);
          formEquat.setRouteSeq(nextRouteSeq);
          formEquat.setRouteName(elementArr[0]);
          formEquat.setDefaultFlag(elementArr[1]);
          formEquat.setOperand1(elementArr[2]);        
          formEquat.setOperand2(elementArr[3]);
          formEquat.setCompare(elementArr[4]);
          formEquat.setFormEquation(elementArr[5]);
          formEquat.setOperationType(elementArr[6]);
          formEquat.setDateFormat(elementArr[7]);
          formEquatDAO.insertObject(formEquat);
          int seqID = nextRouteSeq.intValue()-1;
          mtmWorkflowStepWorkflowStep.setParentType(WorkflowStep.PARENT_TYPE_SINGLE + seqID);
        } else {
          mtmWorkflowStepWorkflowStep.setParentType(parentStepType[i]);
        }
        mtmWorkflowStepWorkflowStep.setParentStepID(parentStepID);
        Integer childStepID = stepDAO.getStepIDByWorkflowIDAndStepSeq(new Integer(workflowRecordID), new Integer(childStepSeq[i]));
        mtmWorkflowStepWorkflowStep.setChildStepID(childStepID);        
        //mtmWorkflowStepWorkflowStep.setLoopBack(loopBack[i]);
        Integer nextGroupID = stepStepDAO.getNextGroupIDForWorkflowRecord(new Integer(workflowRecordID));
        if (nextGroupID == null) {
          nextGroupID = new Integer(1);
        }
        mtmWorkflowStepWorkflowStep.setGroupID(nextGroupID);
        List childstepList = stepStepDAO.getListByChildStepID(childStepID);
        if(childstepList==null||childstepList.size()==0){
          mtmWorkflowStepWorkflowStep.setLoopBack(MtmWorkflowStepWorkflowStep.LOOP_BACK_NO);
        } else {
          mtmWorkflowStepWorkflowStep.setLoopBack(MtmWorkflowStepWorkflowStep.LOOP_BACK_YES);
        }
        stepStepDAO.insertObject(mtmWorkflowStepWorkflowStep);
        
        //update the actionType of the parent's step depending on the connection type
        stepDAO.updateStepTypeByID(parentStepID, parentStepActionType[i]);
//        if(WorkflowStep.PARENT_TYPE_ROUTINE.equals(parentStepType[i])  ) {
//          this.insertWorkflowStepRoutine(request,parentStepID);
//        }
    }
    }catch(Exception e){
      throw new ApplicationException(e);   
    }
    // if the step action type is ACTION_TYPE_USER_DEFINED_TASK,
    // then insert the routine into Worklow_Step_Routine table for this step
    /*if(WorkflowStep.ACTION_TYPE_USER_DEFINED_TASK.equals(step.getActionType())  ) {
      this.insertWorkflowStepRoutine(request,step.getID());    
      
    // if the step action type is ACTION_TYPE_FORM_DRIVEN,
    // then insert the form equation into Workflow_Step_Form_Equat table for this step  
    } else if(WorkflowStep.ACTION_TYPE_FORM_DRIVEN.equals(step.getActionType()) ){
      this.insertWorkflowStepFormEquat(request,step.getID());  
    }*/        
    
  }
  
  /**
   * Insert route of this step into Workflow_Step_Routine by stepID
   * @param request
   * @param stepID
   * @throws ApplicationException
   */
  private void insertWorkflowStepRoutine(
        HttpServletRequest request,  
        Integer stepID) throws ApplicationException {
    WorkflowStepRouteDAObject wfStepRouteDAO = (WorkflowStepRouteDAObject) this.getDAObjectByClassName(request, "com.dcivision.workflow.dao.WorkflowStepRouteDAObject");
           
    //  Insert route name into Workflow_Step_Route table
    String  routeListValue = request.getParameter("routeListValue");
    if(!Utility.isEmpty(routeListValue) && !"null".equals(routeListValue) ){
      String[] routineArr = TextUtility.splitString(routeListValue,"|");
      for(int i=0; i<routineArr.length; i++){
        WorkflowStepRoute tmpRoutine = new WorkflowStepRoute();
        tmpRoutine.setWorkflowStepID(stepID);
        tmpRoutine.setRouteSeq(new Integer(i));
        tmpRoutine.setRouteName(routineArr[i]);
        wfStepRouteDAO.insertObject(tmpRoutine);
      }
    }
    
  }
  
  /**
   * Insert Wrokflow Step Form Equation
   * @param request
   * @param stepID
   * @throws ApplicationException
   */
  private void insertWorkflowStepFormEquat(
        HttpServletRequest request,
        Integer stepID) throws ApplicationException {
    WorkflowStepFormEquatDAObject formEquatDAO = (WorkflowStepFormEquatDAObject) this.getDAObjectByClassName(request, "com.dcivision.workflow.dao.WorkflowStepFormEquatDAObject");

    //Insert the form equation into Workflow_Step_Form_Equation Table
    String formEquationListValue = request.getParameter("formEquationListValue");

    String[] formEquationArr = TextUtility.splitString(formEquationListValue, "$$");
    for(int i=0; i<formEquationArr.length; i++){
      String[] elementArr = TextUtility.splitString(formEquationArr[i],";");
      //if(!Utility.isEmpty(compare)){
        WorkflowStepFormEquat formEquat = new WorkflowStepFormEquat();
        formEquat.setWorkflowStepID(stepID);
        formEquat.setRouteSeq(new Integer(i+1));
        formEquat.setRouteName(elementArr[0]);
        formEquat.setDefaultFlag(elementArr[1]);
        formEquat.setOperand1(elementArr[2]);        
        formEquat.setOperand2(elementArr[3]);
        formEquat.setCompare(elementArr[4]);
        formEquat.setFormEquation(elementArr[5]);
        formEquat.setOperationType(elementArr[6]);
        formEquat.setDateFormat(elementArr[7]);
        formEquatDAO.insertObject(formEquat);

      //}
      
    }

  }

}
